package com.etc.cure.service.Impl;

import cn.hutool.json.JSONUtil;
import com.etc.common.mapper.LogMapper;
import com.etc.common.utils.Result;
import com.etc.common.utils.UUIDUtil;
import com.etc.cure.entity.Hospital;
import com.etc.cure.mapper.HospitalMapper;
import com.etc.cure.service.HospitalService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.List;

import static com.etc.common.utils.RedisConstants.CACHE_INHOSPITAL;

@Service
public class HospitalServiceImpl implements HospitalService {
    @Resource
    private HospitalMapper hospitalMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private LogMapper logMapper;

    @Override
    public Result queryByDocId(Integer pageNum, Integer pageSize, String docId) {
        //判断redis中是否有缓存
        Boolean isExist = stringRedisTemplate.hasKey(CACHE_INHOSPITAL + ":docId:" + docId);
        if (!isExist) {
            //如果没有缓存，从数据库中获取数据
            List<Hospital> list = hospitalMapper.queryByDocId(docId);
            for (Hospital hospital : list) {
                //转化成json
                String jsonStr = JSONUtil.toJsonStr(hospital);
                //写入redis
                stringRedisTemplate.opsForList().leftPush(CACHE_INHOSPITAL + ":docId:" + docId, jsonStr);
            }
        }
        //如果有缓存，直接从缓存中获取数据
        List<String> json = stringRedisTemplate.opsForList().range(CACHE_INHOSPITAL + ":docId:" + docId,
                pageSize * (pageNum - 1), pageSize * (pageNum - 1) + pageSize - 1);
        //转化成list
        List<Hospital> list = JSONUtil.toList(json.toString(), Hospital.class);
        return Result.ok(list);
    }

    @Override
    public Result queryByOsId(String osId) {
        return Result.ok(hospitalMapper.queryByOsId(osId));
    }

    @Override
    @Transactional
    public Result insert(String osId,String docId) {
        //判断是否有门诊id在数据库
        Hospital result = hospitalMapper.queryByOsId(osId);
        if (result != null) {
            //如果有，直接返回
            return Result.fail(0, "该病人已存在住院信息");
        }
        //设置住院id
        hospitalMapper.insert(UUIDUtil.getUUID(),osId);
        //删除redis中的缓存
        stringRedisTemplate.delete(CACHE_INHOSPITAL + ":docId:" + docId);
        //写入日志
        logMapper.insert(UUIDUtil.getUUID(),docId,"新增住院信息");
        return Result.ok(1);
    }

    @Override
    public Result update(Hospital hospital, String docId) {
        hospitalMapper.update(hospital);
        //删除redis中的缓存
        stringRedisTemplate.delete(CACHE_INHOSPITAL + ":docId:" + docId);
        //写入日志
        logMapper.insert(UUIDUtil.getUUID(),docId,"修改住院信息");
        return Result.ok(1);
    }
}
